//
//  CLUserInfoViewController.m
//  chanlin
//
//  Created by Ryan on 14-12-21.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLUserInfoViewController.h"
#import "BlockUI.h"
#import "UIImageView+WebCache.h"
#import "UIView+Utils.h"
#import "CLLoginModel.h"
#import "ImageEdit.h"
#import "IGTMBase64.h"
#import "SgrGCD.h"
#import "ChangyanSDK.h"

@interface CLUserInfoViewController ()

@property (nonatomic,strong)UIButton *backButton;
@property (nonatomic,strong)UIButton *edit;
@property (nonatomic,strong) UIImageView *icon;
@property (nonatomic,strong) UIButton *title;
@property (nonatomic,strong) UILabel *uname;
@property (nonatomic,strong) UIView *headChange;
@property (nonatomic,strong) UIButton *mark;
@property (nonatomic,unsafe_unretained)CGRect rect_m;

@end

@implementation CLUserInfoViewController

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.backButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:[UIImage imageNamed:@"tb_back.png"] forState:UIControlStateNormal];
    self.backButton.contentEdgeInsets=UIEdgeInsetsMake(7, 7, 7, 7);
    self.backButton.frame=CGRectMake(15.f, 20.f, 44.f, 44.f);
    __weak typeof(self) me=self;
    [self.backButton handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [me.dispatchObj pop];
    }];
    [self.view addSubview:self.backButton];
    
    self.edit=[UIButton buttonWithType:UIButtonTypeCustom];
    self.edit.titleLabel.font=[UIFont systemFontOfSize:19];
    self.edit.frame=CGRectMake(GlobleWidth-65.f, 32.f, 50.f, self.edit.titleLabel.font.lineHeight);
    [self.edit setTitleColor:RGB(98, 101, 113) forState:UIControlStateNormal];
    [self.edit setTitle:@"注销" forState:UIControlStateNormal];
//    [self.edit setTitle:@"完成" forState:UIControlStateSelected];
//    [self.edit setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    
    [self.edit handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [CLGloble sharedInstance].user=nil;
        [ChangyanSDK logout];
        [me.dispatchObj pop];
        [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"注销成功"];
      
        
    }];
    
    
    [self.view addSubview:self.edit];
    
    UILabel *title=[[UILabel alloc] init];
    title.font=[UIFont systemFontOfSize:20];
    title.frame=CGRectMake((GlobleWidth-100.f)/2.f, 30.f, 100.f, title.font.lineHeight);
    title.textColor=RGB(98, 101, 113);
    title.textAlignment=NSTextAlignmentCenter;
    title.text=@"用户信息";
    
    [self.view addSubview:title];
    
    CALayer *line=[CALayer layer];
    line.backgroundColor=title.textColor.CGColor;
    line.frame=CGRectMake(0, 64.f, GlobleWidth, 0.5);
    [self.view.layer addSublayer:line];
    
    
    self.icon=[[UIImageView alloc] initWithFrame:CGRectMake((GlobleWidth-60.f)/2.f, 90.f, 60.f, 60.f)];
    self.icon.layer.cornerRadius=30.f;
    self.icon.userInteractionEnabled=YES;
    self.icon.clipsToBounds=YES;
    [self.view addSubview:self.icon];
    self.icon.userInteractionEnabled=YES;
    UITapGestureRecognizer *recoginzer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeImg)];
    [self.icon addGestureRecognizer:recoginzer];
    
    
    self.chan=[[UIImageView alloc] initWithFrame:CGRectMake(self.icon.width-18, self.icon.height-18, 18, 18)];
    self.icons=@[@"groupId_1_b.png",@"groupId_2_b.png",@"groupId_3_b.png"];
    
    int index=[[CLGloble sharedInstance].user.groupId intValue]-2;
    
    if(index>=0){
        CGRect frame=[self.icon convertRect:CGRectMake(self.icon.width-16, self.icon.height-16, 18, 18) toView:self.view];
        self.chan.frame=frame;
        [self.view addSubview:self.chan];
        
        self.chan.image=[UIImage imageNamed:[self.icons sgrGetStringForIndex:index]];
    }else{
        [self.chan removeFromSuperview];
    }
    
    self.uname=[[UILabel alloc] init];
    self.uname.font=[UIFont systemFontOfSize:18];
    
    self.uname.frame=CGRectMake((GlobleWidth-200.f)/2.f, self.icon.bottom+15.f, 200.f, self.uname.font.lineHeight);
    self.uname.textAlignment=NSTextAlignmentCenter;
    self.uname.textColor=RGB(98, 101, 113);
    [self.view addSubview:self.uname];
    self.uname.userInteractionEnabled=YES;
    recoginzer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeName)];
    [self.uname addGestureRecognizer:recoginzer];
    
    if(_isStrNotNull([CLGloble sharedInstance].user.imgUrl)){
        [self.icon sd_setImageWithURL:
         [NSURL URLWithString:[CLGloble sharedInstance].user.imgUrl]
                     placeholderImage:nil];
       // self.uname.text=[CLGloble sharedInstance].user.nickName;
    }
    self.uname.text=[CLGloble sharedInstance].user.nickName;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    self.rect_m=CGRectMake(0, GlobleHeight, GlobleWidth, 150.f);

}

- (void)uploadImg:(UIImage *)image{
    CGSize targetSize=CGSizeMake(120.0f, 120.0f);
    UIImage *theImage = [ImageEdit baseImageBycllipFromTopAndMiddleForSize:targetSize Image:image placeHoldImage:nil Align:2];
    UIImage *returnImg = [ImageEdit cutImage:theImage targetSize:targetSize];
    NSData *data=UIImageJPEGRepresentation(returnImg,1.0);
    NSString *str=[IGTMBase64 stringByEncodingData:data];
    __weak typeof(self) me=self;
    
    [[CLLoginModel sharedInstance] editImg:str nickName:nil uiBlock:^(BOOL success, id responseObj, NSString *message) {
        if(success && [responseObj isKindOfClass:[NSDictionary class]]){
            
            //[CLGloble sharedInstance].user.nickName=[responseObj sgrGetStringForKey:@"nickname"];
            NSString *imgurl=[responseObj sgrGetStringForKey:@"userpic"];
            if(_isStrNotNull(imgurl))
            [CLGloble sharedInstance].user.imgUrl=imgurl;
            
            if(_isStrNotNull([CLGloble sharedInstance].user.imgUrl)){
                [me.icon sd_setImageWithURL:
                 [NSURL URLWithString:[CLGloble sharedInstance].user.imgUrl]
                             placeholderImage:nil];
                // self.uname.text=[CLGloble sharedInstance].user.nickName;
            }
            [[CLGloble sharedInstance].user save];
            [[SgrGCD sharedInstance] enqueueGloble:^{
                if(_isStrNotNull([CLGloble sharedInstance].user.token)){
                    [ChangyanSDK loginSSO:[CLGloble sharedInstance].user.uid
                                 userName:[CLGloble sharedInstance].user.nickName
                               profileUrl:[NSString stringWithFormat:@"groupId=%@",_safeStr([CLGloble sharedInstance].user.groupId)]
                                   imgUrl:[CLGloble sharedInstance].user.imgUrl
                            completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                                if(statusCode!=CYSuccess){
                                    [[CLGloble sharedInstance] showTieSuccessMessage:@"同步评论登陆失败"
                                                                          subMessage:@"建议注销重新登陆尝试"];
                                }
                            }];
                }
            }];

            
        }else{
            [[CLGloble sharedInstance] showTieAlertMessage:@"修改失败" subMessage:@"建议尝试下注销重新登陆再修改"];
        }
    }];
}

- (void)changeUserName:(NSString *)name{
    if(_isStrNULL(name)){
        [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"昵称不能为空"];
        return;
    }
    
    if([name length]>25){
        [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:@"昵称不能多余25个字"];
        return;

    }
    
    [self.mark removeFromSuperview];
    self.mark=nil;
    [self.headChange removeFromSuperview];
    self.headChange=nil;
    
    __weak typeof(self) me=self;
    [[CLLoginModel sharedInstance] editImg:nil nickName:name uiBlock:^(BOOL success, id responseObj, NSString *message) {
        if(success && [responseObj isKindOfClass:[NSDictionary class]]){
            
            //[CLGloble sharedInstance].user.nickName=[responseObj sgrGetStringForKey:@"nickname"];
            NSString *name=[responseObj sgrGetStringForKey:@"nickname"];
            if(_isStrNotNull(name))
                [CLGloble sharedInstance].user.nickName=name;
            
            me.uname.text=[CLGloble sharedInstance].user.nickName;
            [[CLGloble sharedInstance].user save];
            [[SgrGCD sharedInstance] enqueueGloble:^{
                if(_isStrNotNull([CLGloble sharedInstance].user.token)){
                    [ChangyanSDK loginSSO:[CLGloble sharedInstance].user.uid
                                 userName:[CLGloble sharedInstance].user.nickName
                               profileUrl:[NSString stringWithFormat:@"groupId=%@",_safeStr([CLGloble sharedInstance].user.groupId)]
                                   imgUrl:[CLGloble sharedInstance].user.imgUrl
                            completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                                if(statusCode!=CYSuccess){
                                    [[CLGloble sharedInstance] showTieSuccessMessage:@"同步评论登陆失败"
                                                                          subMessage:@"建议注销重新登陆尝试"];
                                }
                            }];
                }
            }];

           
        }else{
            [[CLGloble sharedInstance] showTieAlertMessage:@"修改失败" subMessage:@"建议尝试下注销重新登陆再修改"];
        }
    }];
}

- (BOOL)showPopAction{
    return YES;
}

- (void)changeName{
    self.mark=[UIButton buttonWithType:UIButtonTypeCustom];
    self.mark.backgroundColor=[UIColor blackColor];
    self.mark.alpha=0.5;
    self.mark.frame=self.view.bounds;
    self.headChange=[[UIView alloc] initWithFrame:self.rect_m];
    self.headChange.backgroundColor=[UIColor whiteColor];
    
    
    [self.view addSubview:self.mark];
    [self.view addSubview:self.headChange];
    
    __weak typeof(self) me=self;
    
    UIButton *button1=[UIButton buttonWithType:UIButtonTypeCustom];
    button1.layer.borderWidth=0.5;
    button1.layer.borderColor=RGB(98, 101, 113).CGColor;
    button1.layer.cornerRadius=5.f;
    button1.titleLabel.font=[UIFont systemFontOfSize:19];
    button1.frame=CGRectMake((GlobleWidth-160.f)/3.f, 100, 80, 30);
    [button1 setTitleColor:RGB(98, 101, 113) forState:UIControlStateNormal];
    [button1 setTitle:@"确定" forState:UIControlStateNormal];
    [self.headChange addSubview:button1];
    
    
    UITextField *text=[[UITextField alloc] initWithFrame:CGRectMake(15.f, 40.f, 290.f, 35)];
    text.layer.borderWidth=0.5;
    text.layer.borderColor=RGB(98, 101, 113).CGColor;
    button1.layer.cornerRadius=5.f;
    [self.headChange addSubview:text];
    
    [button1 handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [me changeUserName:text.text];
    }];
    
    UIButton *button2=[UIButton buttonWithType:UIButtonTypeCustom];
    button2.layer.borderWidth=0.5;
    button2.layer.borderColor=RGB(98, 101, 113).CGColor;
    button2.layer.cornerRadius=5.f;
    button2.titleLabel.font=[UIFont systemFontOfSize:19];
    button2.frame=CGRectMake(GlobleWidth-(GlobleWidth-160.f)/3.f-80.f, 100, 80, 30);
    [button2 setTitleColor:RGB(98, 101, 113) forState:UIControlStateNormal];
    [button2 setTitle:@"取消" forState:UIControlStateNormal];
    [self.headChange addSubview:button2];
    
   
    
    [button2 handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [me.mark removeFromSuperview];
        me.mark=nil;
        [me.headChange removeFromSuperview];
        me.headChange=nil;
    }];
    
    
    [UIView animateWithDuration:0.3 animations:^{
        self.headChange.frame=CGRectMake(0, GlobleHeight-150.f, GlobleWidth, 150.f);
    } completion:^(BOOL finished) {
        
        __weak UIButton *b=self.mark;
        [self.mark handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
            [b removeFromSuperview];
            me.mark=nil;
            [me.headChange removeFromSuperview];
            me.headChange=nil;
        }];
    }];

}

- (void)changeImg{
    self.mark=[UIButton buttonWithType:UIButtonTypeCustom];
    self.mark.backgroundColor=[UIColor blackColor];
    self.mark.alpha=0.5;
    self.mark.frame=self.view.bounds;
    self.headChange=[[UIView alloc] initWithFrame:self.rect_m];
    self.headChange.backgroundColor=[UIColor whiteColor];
      __weak typeof(self) me=self;
    UIButton *button1=[UIButton buttonWithType:UIButtonTypeCustom];
    button1.layer.borderWidth=0.5;
    button1.layer.borderColor=RGB(98, 101, 113).CGColor;
    button1.layer.cornerRadius=5.f;
    button1.titleLabel.font=[UIFont systemFontOfSize:19];
    button1.frame=CGRectMake((GlobleWidth-160.f)/3.f, 40, 80, 30);
    [button1 setTitleColor:RGB(98, 101, 113) forState:UIControlStateNormal];
    [button1 setTitle:@"相册" forState:UIControlStateNormal];
    [self.headChange addSubview:button1];
    [button1 handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [me.mark removeFromSuperview];
        me.mark=nil;
        [me.headChange removeFromSuperview];
        me.headChange=nil;

        [me userSelectPicWithType:UIImagePickerControllerSourceTypePhotoLibrary result:^(UIImage* image){
            [me uploadImg:image];
           
              }];
   }];
    
    UIButton *button2=[UIButton buttonWithType:UIButtonTypeCustom];
    button2.layer.borderWidth=0.5;
    button2.layer.borderColor=RGB(98, 101, 113).CGColor;
    button2.layer.cornerRadius=5.f;
    button2.titleLabel.font=[UIFont systemFontOfSize:19];
    button2.frame=CGRectMake(GlobleWidth-(GlobleWidth-160.f)/3.f-80.f, 40, 80, 30);
    [button2 setTitleColor:RGB(98, 101, 113) forState:UIControlStateNormal];
    [button2 setTitle:@"拍照" forState:UIControlStateNormal];
    [self.headChange addSubview:button2];
     [button2 handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
         [me.mark removeFromSuperview];
         me.mark=nil;
         [me.headChange removeFromSuperview];
         me.headChange=nil;
         
         [me userSelectPicWithType:UIImagePickerControllerSourceTypeCamera result:^(UIImage* image){
             [me uploadImg:image];
         }];
     }];
    
    UIButton *button3=[UIButton buttonWithType:UIButtonTypeCustom];
    button3.layer.borderWidth=0.5;
    button3.layer.borderColor=RGB(98, 101, 113).CGColor;
    button3.titleLabel.font=[UIFont systemFontOfSize:19];
    button3.frame=CGRectMake(0, 110.f, GlobleWidth, 40);
    [button3 setTitleColor:RGB(98, 101, 113) forState:UIControlStateNormal];
    [button3 setTitle:@"取消" forState:UIControlStateNormal];
    [self.headChange addSubview:button3];
    [button3 handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [me.headChange removeFromSuperview];
        me.mark=nil;
        [me.headChange removeFromSuperview];
        me.headChange=nil;
    }];
    
    
    [self.view addSubview:self.mark];
    [self.view addSubview:self.headChange];
    [UIView animateWithDuration:0.3 animations:^{
        self.headChange.frame=CGRectMake(0, GlobleHeight-150.f, GlobleWidth, 150.f);
    } completion:^(BOOL finished) {
      
        __weak UIButton *b=self.mark;
        [self.mark handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
            [b removeFromSuperview];
            me.mark=nil;
            [me.headChange removeFromSuperview];
            me.headChange=nil;
        }];
    }];
    
}

#pragma mark -
#pragma mark - 键盘显示、隐藏通知事件
-(void)showKeyboard:(NSNotification *)aNotification{
    

    
    if(!self.headChange) return;
    
    
    
    NSDictionary *userInfo = aNotification.userInfo;
    
    //
    // Get keyboard size.
    
    NSValue *beginFrameValue = userInfo[UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardBeginFrame = [[self k_mainWindow] convertRect:beginFrameValue.CGRectValue fromView:nil];
    
    NSValue *endFrameValue = userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardEndFrame = [[self k_mainWindow] convertRect:endFrameValue.CGRectValue fromView:nil];
    
    //
    // Get keyboard animation.
    
    NSNumber *durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration = durationValue.doubleValue;
    
    NSNumber *curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey];
    UIViewAnimationCurve animationCurve = curveValue.intValue;
    
    //
    // Create animation.
    
    
    
    //    void (^animations)() = ^() {
    //        CGRect rect =keyboardEndFrame;
    //        commentView.frame = CGRectMake(0, rect_m.origin.y-rect.size.height-rect_m.size.height, rect_m.size.width, rect_m.size.height);
    //    };
    
  //  commentView.frame = CGRectMake(0, keyboardBeginFrame.origin.y-rect_m.size.height, rect_m.size.width, rect_m.size.height);
    
    //CGRect frame=self.headChange.frame;
    self.headChange.frame=CGRectMake(0, keyboardBeginFrame.origin.y-_rect_m.size.height, _rect_m.size.width, _rect_m.size.height);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    [UIView setAnimationBeginsFromCurrentState:YES];
    CGRect rect =keyboardEndFrame;
 
    
    self.headChange.frame = CGRectMake(0, rect.origin.y-_rect_m.size.height, _rect_m.size.width, _rect_m.size.height);
//    self.backGroundButton.alpha = 0.5;
    [UIView commitAnimations];
    
    
    
  
}
-(void)hiddenKeyboard:(NSNotification *)info{
    if(!self.headChange) return;
  
    [UIView animateWithDuration:0.25 animations:^{
        self.headChange.frame = CGRectMake(0, _rect_m.origin.y, _rect_m.size.width, _rect_m.size.height);
            } completion:^(BOOL finished) {
    
    }];
}






@end
